package com.diandireader.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.diandireader.domain.DiandiReaderVO;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
/**
 * 文件操作帮助类
 * @author mayh
 *
 */
public class FileHelper {

	//根目录
	public static final String sdFileForderName = "diandiReader";
	//书籍目录
	public static final String diandiReaderBooks = sdFileForderName+"/books";
	//数据库目录
	public static final String diandiReaderDb = sdFileForderName+"/db";
	//最小空间
	private static final int availableBlocks = 2;
	//文件类型
	public static String IMAGE = "image";//图片
	public static String TXT = "txt";//文本
	public static String PDF = "pdf";//pdf
	public static String ZIP = "zip";//压缩包
	public static String FOLDER = "folder";//压缩包
	public static String UNKNOWN = "unknown";//未知格式
	//设置当前支持的文件格式
	public static List<String> allowTypeList = new ArrayList<String>(){{
		add("txt");
		add("xml");
		add("png");
		add("bmp");
		add("jpeg");
		add("jpg");
		add("gif");
		add("ico");
	}};
	//获得系统的存储目录，如果有SD卡，则返回SD卡的目录，如果没有SD卡，则返回手机内存目录
	public static String getStrogeFolder(){
		String strogeFolder = null;
		//首先判断SD卡的访问权限
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
			//获得SD卡的路径
			strogeFolder = Environment.getExternalStorageDirectory().getPath();
		}else {
		//如果没有内存卡，就获得手机内存地址
			strogeFolder = Environment.getRootDirectory().getPath();
		}
		//判断SD卡的剩余空间
		StatFs statFs = new StatFs(strogeFolder);
		//可用的块*每一块的大小/(1024*1024) = MB
		if(Math.abs(statFs.getAvailableBlocks()*statFs.getBlockSize()/(1024*1024))<availableBlocks){
			L.d("内存不足");
			return null;
		}
		return strogeFolder;
	}
	
	//获得文件的修改时间
	public static String getFileModifyTime(File file){
		String createTime = "";
		if(file!=null){
			long times  = file.lastModified();
			Date date = new Date(times);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			createTime = sdf.format(date);
		}
		return createTime;
	}
	
	//获得编码格式
	public static String getFileEncodeType(File file){
		String encodeName = "gb2312";
		if(file!=null){
			byte buffer[] = new byte[3];
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				fis.read(buffer);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		if(buffer[0] == -1 && buffer[1] == -2 )  
            encodeName = "UTF-16";  
        if (buffer[0] == -2 && buffer[1] == -1 )  
            encodeName = "UNICODE";  
        if(buffer[0]==-17 && buffer[1]==-69 && buffer[2] ==-65)  
            encodeName = "UTF-8";  
		}
		return encodeName;
	}
	
	//读取Bitmap
	public static Bitmap readBitmap(String path){
		return BitmapFactory.decodeFile(path);
	}
	
	//读取drawable
	public static Drawable readDrawable(String path){
		return Drawable.createFromPath(path);
	}
	
	//获得文件的类型
	public static String getFileType(File file){
		String type = "txt";
		if(file!=null){
			//如果是文件
			if(file.isFile()){
				//获得文件的后缀名
				String suffix  = getFileSuffix(file);
				if("txt".equals(suffix)||"xml".equals(suffix)){
					type = TXT;
				}else if("pdf".equals(suffix)){
					type = PDF;
				}else if("png".equals(suffix)||"jpg".equals(suffix)||"jpeg".equals(suffix)||"bmp".equals(suffix)||"gif".equals(suffix)||"ico".equals(suffix)){
					type = IMAGE;
				}else if("rar".equals(suffix)||"zip".equals(suffix)||"tar".equals(suffix)){
					type = ZIP;
				}else if("folder".equals(suffix)){
					type = FOLDER;
				}else {
					type = UNKNOWN;
				}
			}
		}
		return type;
	}
	
	//获得文件后缀
	public static String getFileSuffix(File file){
		String suffix = "";
		if(file!=null){
			if(file.isFile()){
			String fileName = file.getName();
		    suffix  = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()).toLowerCase();
			}else if(file.isDirectory()){
				suffix = "folder";
			}
		}
		return suffix;
	}
	//去掉文件后缀
	public static String getFileWithoutSuffix(String fileName){
		String str = "";
		if(fileName!=null){
			str = fileName.substring(0, fileName.lastIndexOf("."));
		}
		return str;
	}
	
	//获得文件大小
	public static String getFileSize(File file){
		String size = "0B";
		if(file!=null){
			try {
				//格式化 显示样式
				DecimalFormat format = new DecimalFormat("0.00");
				double length = getFileLength(file);
				double tempSize ;
				tempSize = length/1024/1024;
				if(tempSize>=1){
					return size = format.format(tempSize)+"M";
				}
				tempSize = length/1024;
				if(tempSize>=1){
					return size = format.format(tempSize)+"K";
				}
				tempSize = length;
				if(tempSize>=1){
					return size = format.format(tempSize)+"B";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return size;
	}
//	获得文件长度
	public static int getFileLength(File file){
		if(file==null)
			return 0;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			//file.length is only worked in txt
			return fis.available();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	//删除文件
	public static boolean deleteFile(File file){
		boolean flag = true;
		if(file!=null&&file.exists()){
			try{
				file.delete();
			}catch(Exception e){
				flag = false;
			}
		}
		return flag;
	}
	//copy 文件(将输入流写到指定文件)
	public static boolean copyFile(InputStream inputStream,File file){
		if(inputStream==null||file==null)
			return false;
		FileOutputStream fos = null;
		try {
			if(!file.exists()){
				if(!file.createNewFile())return false;
			}
			fos = new FileOutputStream(file);
			byte[] buffer = new byte[255];
			int size = 0;
			while((size = inputStream.read(buffer))>0){
				fos.write(buffer, 0, size);
			}
		}catch(Exception exception){
			exception.printStackTrace();
			return false;
		}finally {
			try {
				fos.flush();
				fos.close();
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
	
	//create index for the book
	public static  class IndexCreator extends Thread{
		private Context context;
		private String path;
		public IndexCreator(Context context,String path){
			this.context = context;
			this.path = path;
		}
		
		@Override
		public void run() {
			System.out.println("开始计算");
			if(path==null||"".equals(path))
				return;
			File file = new File(path);
			FileReader reader = null;
			try {
				reader = new FileReader(file);
				char[] buffer = new char[1024]; 
				long totalChars = 0;
				long flag = 0;
				while((flag=reader.read(buffer))!=-1){
					if(flag!=-1)
					totalChars+=flag;
				}
				SharedPreferences readPositionPreference = context.getSharedPreferences(DiandiReaderVO.READPOSITION, Context.MODE_PRIVATE);
				Editor edit = readPositionPreference.edit();
				edit.putLong("T"+file.getName(), totalChars);
				edit.commit();
				System.out.println("totalChars"+totalChars);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
